package com.ilop.sthome.mvp.present.device;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.aliyun.iot.aep.sdk.apiclient.callback.IoTResponse;
import com.example.common.mvp.BasePresenterImpl;
import com.example.xmpic.ui.utils.CameraDaoUtil;
import com.ilop.sthome.common.command.SendDeviceCommand;
import com.ilop.sthome.data.bean.VirtualUserBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.data.greenDao.RoomBean;
import com.ilop.sthome.mvp.contract.device.RoomManageContract;
import com.example.xmpic.mvp.model.CameraModel;
import com.ilop.sthome.mvp.model.CommonModel;
import com.example.xmpic.mvp.model.CameraModelImpl;
import com.ilop.sthome.mvp.model.common.CommonModelImpl;
import com.example.common.mvp.onModelCallBack;
import com.ilop.sthome.utils.ConfigureUtil;
import com.ilop.sthome.utils.ParsingJsonUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.RoomDaoUtil;
import com.siterwell.familywellplus.R;

import java.util.List;

/**
 * @author skygge
 * @date 2020/5/12.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class RoomManagePresenter extends BasePresenterImpl<RoomManageContract.IView> implements RoomManageContract.IPresent {
    private static final String TAG = RoomManagePresenter.class.getSimpleName();
    private Context mContext;
    private String mDeviceName;
    private int mDeviceId;
    private DeviceInfoBean mDevice;
    private RoomBean mRoom;
    private CommonModelImpl mModel;
    private Handler mHandler;
    private RoomBean mSelectRoom;
    private int mNewPosition;
    private int mOldPosition;

    public RoomManagePresenter(Context mContext) {
        this.mContext = mContext;
        mHandler = new Handler();
        mModel = new CommonModel(mHandler);
    }

    @Override
    public void refreshUI(String deviceName, int deviceId) {
        this.mDeviceName = deviceName;
        this.mDeviceId = deviceId;
        if (!TextUtils.isEmpty(mDeviceName)){
            mView.showIsModifyRoom();
            mDevice = DeviceDaoUtil.getInstance().findByDeviceId(mDeviceName, mDeviceId);
            mRoom = RoomDaoUtil.getInstance().getRoomByRoomId(mDevice.getRoom_id());
        }
    }

    @Override
    public void onSaveChange() {
        if (mOldPosition == mNewPosition){
            mView.bindSuccess();
        }else {
            if (mDeviceId == 0){
                modifyGatewayRoom();
            }else if (mDeviceId == -1){
                modifyCameraRoom();
            }else {
                modifySubDeviceRoom();
            }
        }
    }

    @Override
    public void getRoomListByAccount() {
        mModel.onQueryRoomList(1, 100, new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                if (response.getCode() == 200) {
                    List<VirtualUserBean> userList = ParsingJsonUtil.getInstance().getRoomAndCameraList(response.getData());
                    if (userList!=null) {
                        new Thread(() -> RoomDaoUtil.getInstance().getRoomData(mContext, userList)).start();
                    }
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    @Override
    public void getCurrentRoom(List<RoomBean> mList) {
        if (mRoom == null){
            mView.showCurrentRoom(-1);
            this.mOldPosition = -1;
            this.mNewPosition = -1;
        }else {
            int number = mList.size();
            for (int i = 0; i < number; i++) {
                if (mRoom == mList.get(i)) {
                    mView.showCurrentRoom(i);
                    this.mOldPosition = i;
                    this.mNewPosition = i;
                    break;
                }
            }
        }
    }

    @Override
    public void setSelectRoom(RoomBean mRoom, int position){
        this.mSelectRoom = mRoom;
        this.mNewPosition = position;
    }

    @Override
    public void modifyGatewayRoom() {
        SendDeviceCommand mSend = new SendDeviceCommand(mContext, mDevice);
        mSend.queryOrSetGatewayInfo("01", mSelectRoom.getRid());
    }

    @Override
    public void modifySubDeviceRoom() {
        DeviceInfoBean mGateway = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
        SendDeviceCommand mSend = new SendDeviceCommand(mContext, mGateway);
        mSend.modifySubDeviceRoom(mDevice.getDevice_ID(), mSelectRoom.getRid());
    }

    @Override
    public void modifyCameraRoom() {
        CameraModelImpl mModel = new CameraModel(mHandler);
        mModel.toUpdateCameraRoom(mDevice.getDeviceOnly(), mSelectRoom.getRid(), new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                if (response.getCode() == 200) {
                    modifyCameraSuccess(mSelectRoom);
                }else {
                    mHandler.post(()->mView.showToastMsg(response.getLocalizedMsg()));
                }
            }

            @Override
            public void onFailure(Exception e) {
                mHandler.post(()->mView.showToastMsg(mContext.getString(R.string.failed)));
            }
        });
    }

    @Override
    public void modifySuccess(String roomId) {
        mDevice.setRoom_id(roomId);
        DeviceDaoUtil.getInstance().getDeviceDao().update(mDevice);
        mHandler.post(()-> mView.bindSuccess());
    }

    @Override
    public void modifyCameraSuccess(RoomBean room) {
        mDevice.setRoom_id(room.getRid());
        DeviceDaoUtil.getInstance().getDeviceDao().update(mDevice);
        String roomName = room.getNickname()!=null?room.getNickname(): ConfigureUtil.roomName(mContext, room.getRid());
        CameraDaoUtil.getInstance().updateCameraRoom(mDevice.getDeviceOnly(), mDevice.getDeviceName(),room.getRid(), roomName);
        mHandler.post(()-> mView.bindSuccess());
    }
}
